/**----------------------------------------------------------*/
/** JS:  cmi_goods_list.js（商品管理--商品信息）           */
/**----------------------------------------------------------*/
var tipc = 'GOODS';
var tipc_start = 'GOODS_STEP_0';
var tipc_add_variety = 'GOODS_VARIETY';
var tipc_add_brand = 'GOODS_BRAND'; 
var tipc_add_categroy = 'GOODS_CATEGROY';
var tipc_add_properties = 'GOODS_CATEGROY_PROPERTIES';

var back_goods = function (){
	var p = "innerJump.adm?spt="+menuId+"&st="+tipc_start;
	location.replace(p);
};

var doSave = function() {
	var goods = saveTab1();
	goods = saveTab2(goods);
	goods = saveTab3(goods);
	goods = saveTab4(goods);
	goods = saveTab5(goods);
	goods = saveTab6(goods);
	goods = saveTab7(goods);
	goods = saveTab8(goods);
	
	
	//商品名称 和 商品分类 必填
	if(MyUtils.trim(goods.goodsName).length ==0 || goods.varietyId == '0') {
		MyUtils.waring("商品名称 和 商品分类 不能为空");
		return;
	}
	var form = createSaveForm(MyUtils.toJsonStr(goods));
	jQuery(form).attr('action', 'impl_add/goodsAdd.adm');
	jQuery(form).submit();
	
//	MyUtils.info(MyUtils.toJsonStr(goods));
};
var saveTab1 = function() {
	var goods = {
		 uuid:$('#uuid').val()
		,goodsName:$('#goodsName').val()
		,goodsNameColor:$('#goods_name_color').val()
		,goodsNameFont:$('#goodsNameFont').val()
		,goodsBill:$('#goodsBill').val()
		,varietyId:$('#varietyId').val()
		,extendVarietyId:''
		,brandId:$('#brandId').val()
		,salePrice:getNumber($('#salePrice').val())
		,memberPrice:getNumber($('#memberPrice').val())
		,goodsRate:''
		,marketPrice:getNumber($('#marketPrice').val())
		,saleScore:getNumber($('#saleScore').val())
		,levelScore:getNumber($('#levelScore').val())
		,scoreBy:getNumber($('#scoreBy').val())
		,rate:getNumber($('#rate').val())
		,rateStart:$('#rateStart').datebox("getValue")
		,rateEnd:$('#rateEnd').datebox("getValue")
		,goodsImage_b_url:($('#goodsImage_b_url').val()=='商品图片外部URL') ? "":$('#goodsImage_b_url').val()
		,goodsImage_s_url:($('#goodsImage_s_url').val()=='商品缩略图外部URL') ? "":$('#goodsImage_s_url').val()
	};
	//验证优惠数量 和 价格
	var s_childs = $('input[id*="s_yh_list"]');
	var p_childs = $('input[id*="p_yh_list"]');
	var sval = '';
	var pval = '';
	var list = new Array();
	
	for(var i = 0; i < s_childs.length; i++) {
		sval =  s_childs[i].value;
		pval =  p_childs[i].value;
		if(!MyUtils.trim(sval).length == 0 && !MyUtils.trim(pval) == 0) {
			list.push({s:MyUtils.trim(sval),p:MyUtils.trim(pval)});
		}
	}
	goods.goodsRate = MyUtils.toJsonStr(list);
	return goods;
};

var saveTab2 = function(goods) {
	var editor_data = CKEDITOR.instances.content.getData();
	if (editor_data == null || editor_data == "") {
		goods.detail = '';
	} else {
		goods.detail = editor_data;
	}
	return goods;
};

var saveTab3 = function(goods) {
	goods.goodsWeight = getNumber($('#goodsWeight').val());
	goods.goodsWeightUnit = $('#goodsWeightUnit').val();
	goods.goodsSum = getNumber($('#goodsSum').val());
	goods.goodsWaring = getNumber($('#goodsWaring').val());
	
	goods.goodsBetter = document.getElementById('goodsBetter').checked ? '1' :'0';
	goods.goodsNew = document.getElementById('goodsNew').checked ? '1' :'0'; 
	goods.goodsHot = document.getElementById('goodsHot').checked ? '1' :'0'; 
	goods.goodsDm8 = document.getElementById('goodsDm8').checked ? '1' :'0'; 
	goods.goodsDm1 = document.getElementById('goodsDm1').checked ? '1' :'0'; 
	goods.goodsFreeSend = document.getElementById('goodsFreeSend').checked ? '1' :'0';
	
	goods.goodsKey = $('#goodsKey').val();
	goods.goodsDesc = $('#goodsDesc').val();
	goods.factoryRemark = $('#factoryRemark').val();
	
	return goods;
};

var createSaveForm = function(dts){
	$('#goodsEdit').remove();
	var div = '<div id="goodsEdit" style="display:none;"><iframe name="ifrName" src="" id="ifrName"></iframe></div>';
	jQuery(div).appendTo('body');
	$('#ifrName').load(function() {
		try {
			 var response = this.contentWindow.document.body.textContent;
			 if(!MyUtils.isEmpty(response)){
				var res = MyUtils.toJsonObject(response);
				if(res.error == '0') {
					$.messager.confirm(_msg_sys,MyUtils.valueAlign(res.msg +"是否返回商品列表?","left"), function(r) {
						if(r) {
							back_goods();
						}
					});
				} else {
					MyUtils.error(res.msg);
				}
			 }
		} catch (e) {
			showJsException(e,_msg_fail);
		}
	});
	
	var form = jQuery('<form target="ifrName" action="" method="POST" name="fm" id="fm" enctype="multipart/form-data"></form>');
	var st='<input type="hidden" name="st" id="st" value="'+tipc+'">';
	var dt = '<input type="hidden" name="dt" id="dt" value=\''+dts+'\'>';
	jQuery(st).appendTo(form);
	jQuery(dt).appendTo(form);
	
	//上传商品图片
	var oldElement = jQuery('#goodsImage_b');
	//保证在提交后原来的文件上传框继续存在
	var newElement = jQuery(oldElement).clone();
	jQuery(oldElement).before(newElement);
	
	jQuery(oldElement).attr('name', "goodsImage_b");
	jQuery(oldElement).appendTo(form);
	
	//上传商品缩略图
	oldElement = jQuery('#goodsImage_s');
	newElement = jQuery(oldElement).clone();
	jQuery(oldElement).before(newElement);
	
	jQuery(oldElement).attr('name', "goodsImage_s");
	jQuery(oldElement).appendTo(form);
	
	jQuery(form).appendTo($('#goodsEdit'));		
	return form;
};

var saveTab4 = function(goods) {
	goods.categroyId = $('#categroyId').combobox("getValue");
	goods.fieldsList = '';
	return goods;
};

var saveTab5 = function(goods) {
	
	return goods;
};

var saveTab6 = function(goods) {
	
	return goods;
};

var saveTab7 = function(goods) {
	
	return goods;
};

var saveTab8 = function(goods) {
	
	return goods;
};

$(function(){
	try {
		$('#tabs').tabs({
			tools:[ {"handler":"doSave","iconCls":"icon-set","id":"tb_add","text":"保存提交"}
			        ,'-'
					,{"handler":"back_goods","iconCls":"icon-back","id":"tb_goods","text":"商品列表"}
				]
		});
		$('.tabs').css("background","#fff");
		initTab1();
		initTab2();
		initTab4();
	} catch (e) {
		showJsException(e,_msg_fail);
	}
});

//TODO 通用信息
var initTab1= function() {
	
	//加载商品分类
	getVerietyOptions();
	
	//加载商品品牌
	getBrandOptions();
	
	//加载促销日期
	MyUtils.createChineseDatebox('rateStart');
	MyUtils.createChineseDatebox('rateEnd');
	var current = new Date();
	$('#rateStart').datebox("setValue",MyUtils.getDate(current));
	$('#rateEnd').datebox("setValue",MyUtils.getDate(new Date(current.getFullYear(),(current.getMonth() +12),current.getDate())));
	
	//加载促销价的选择
	$('#rate_ck').live("click",function(){
		var checked = document.getElementById('rate_ck').checked;
		if(checked) {
			$('#rate').removeAttr("readonly");
			$('#rate').css("background","");
		} else {
			$('#rate').css("background","gray");
			$('#rate').attr("readonly","readonly");
		}
	});
};

//TODO 详细描述
var initTab2 = function(){
	CKEDITOR.replace('content',{
		height:screen.height + 'px'
	   ,basePath:"ckfinder/"
	   ,skin: "kama"
	});
};

//TODO 商品属性
var initTab4 = function() {
	
	//加载商品类型
	$('#categroyId').combobox({
		 url:"impl_search/searchObjectList.ajax?st="+tipc_add_categroy+"&qy=" 
		,valueField:"uuid" 
		,textField:"categroy"
	    ,onSelect:function(record) {
	    	getPropertiesList(record);
	    }
		,value:'0'
	});
};

/**
 * 加载 商品分类
 */
var getVerietyOptions = function(){
	$('#varietyId').empty();
	try {
		var getSplitTab = function(times) {
			var nbsp = '&nbsp;&nbsp;&nbsp;&nbsp;';
			var space = '';
			while(times > 0) {
				space +=nbsp;
				times--;
			}
			return space;
		};
		var getVerietyOption = function(datas,index) {
			var div = "";
			for(var i=0;i<datas.length;i++) {
				div +='<option value="'+datas[i].uuid+'">'+(getSplitTab(index) + datas[i].varName)+'</option>';
				if(datas[i].children && datas[i].children.length > 0) {
					div += getVerietyOption(datas[i].children,(index +1));
				}
			}
			return div;
		};
		MyUtils.sendPost("impl_search/searchObjectList.ajax",{qy:'',st:tipc_add_variety},function(msg){
			try{
				var div = '<option value="0">请选择...</option>'
					+ getVerietyOption(MyUtils.toJsonObject(msg),0);
				$('#varietyId').append(div);
			} catch (e) {
				$('#varietyId').empty();
			}
		});
	} catch (e) {
		$('#varietyId').empty();
	}
};

/**
 * 加载 商品品牌
 */
var getBrandOptions = function() {
	$('#brandId').empty();
	try{
		var brandOptions = function(datas){
			var div = "";
			for(var i=0;i<datas.length;i++) {
				div +='<option value="'+datas[i].uuid+'">'+(datas[i].brandName)+'</option>';
			}
			return div;
		};
		MyUtils.sendPost("impl_search/searchObjectList.ajax",{qy:'',st:tipc_add_brand},function(msg){
			try{
				var div = '<option value="0">请选择...</option>'
					+ brandOptions(MyUtils.toJsonObject(msg));
				$('#brandId').append(div);
			} catch (e) {
				$('#brandId').empty();
			}
		});
	} catch (e) {
		$('#brandId').empty();
	}
};
var copytr = function(trId,tha) {
	var tr = $('#'+trId).html();
	var str = '<tr><th><a href="javascript:void(0)" onclick="$(this).parent().parent().remove()">[-]</a>' + tha + ":</th><td>"
		 + $($(tr)[1]).html() + "</td>";
	$('#'+trId).after(str);
};
var getPropertiesList = function(record){
	$('#prop_list').empty();
	try{
		var propertiesList = function(datas){
			var div = "";
			for(var i=0;i<datas.length;i++) {
				var pids= 'p_props_'+i;
				if(datas[i].uuid == '0') {
					continue;
				}
				var inputs = datas[i].inputs;
				var choseAble = datas[i].choseAble;
				
				var content ='';
				var a = '';
				//手工录入
				if(inputs == '1') {
					content = '<input type="text" style="width: 288px;" value="">';
				} 
				//列表中选择
				if(inputs == '2') {
					var optionVal = datas[i].valueList.split("\n");
					content = '<select class="select_st"><option value="">请选择...</option>';
					for(var j=0;j < optionVal.length;j++) {
						content +='<option value="'+optionVal[j]+'">'+optionVal[j]+'</option>';
					}
					content +='</select>';
				} 
				//多行文本框
				if(inputs == '3') {
					content = '<textarea cols="40" rows="3"></textarea>';
				} 
				if(choseAble != '1') {
					a = '<a href="javascript:void(0)" onclick="copytr(\''+pids+'\',\''+datas[i].proName+'\')">[+]</a>';
					content +='<spane>属性价格<input type="text" style="width: 80px;" value=""></span>';
				}
//				div+='<div style="margin-top:5px;padding:5px;">'+ title + a + '<span>' + content + '</span></div>';
				div +='<tr id="'+pids+'"><th>' + a + datas[i].proName+ ':</th>' + '<td><div>' + '<span>' + content + '</span>' + '</div></td></tr>';
			}
			return div;
		};
		
		MyUtils.sendPost("impl_search/searchObjectList.ajax",{qy:record.uuid,st:tipc_add_properties},function(msg){
			try{
				var div = propertiesList(MyUtils.toJsonObject(msg));
				$('#prop_list').append(div);
			} catch (e) {
				$('#prop_list').empty();
			}
		});
	} catch (e) {
		$('#prop_list').empty();
	}
};

/**
 * 关闭 和 显示 div
 */
var showHideDiv = function(id,show) {
	if(show) {
		$('#'+id).show();
	} else{
		$('#'+id).hide();
	}
};

/**
 * 添加 扩展分类
 */
var addExtendVariety = function() {
	var div = '<select name="goods_name_style">'
		+ '<option value="">请选择...</option>'
		+ '<option value="strong">飞利浦</option>'
		+ '<option value="em">松下</option>'
		+ '</select>';
	$('#extendVarietys').append(div);
};

/**
 * 设置 添加的 优惠数量 和 优惠价格 的操作DIV
 */
var appendYhDiv = function(index){
	var div = '<div style="margin-top:5px;">'
		+ '<a href="javascript:void(0)" onclick="javascript:$(this).parent().remove();" >[-]</a>'
		+ '<span style="margin-left:8px;">优惠数量<input type="text"  size=8 id="s_yh_list_'+index+'" class="input" style="width: 100px;" value=""></span>'
		+ '<span style="margin-left:5px;">优惠价格<input type="text"  size=8 id="p_yh_list_'+index+'" class="input" style="width: 100px;" value=""></span>'
		+ '</div>';
	$('#subYh').append(div);
	
};

/**
 * 添加优惠数量 和 优惠价格
 */
var addYh = function() {
	//验证优惠数量 和 价格是否已经填写
	var s_childs = $('input[id*="s_yh_list"]');
	var p_childs = $('input[id*="p_yh_list"]');
	var sval = '';
	var pval = '';
	for(var i = 0; i < s_childs.length; i++) {
		sval =  s_childs[i].value;
		pval =  p_childs[i].value;
		if(MyUtils.trim(sval).length == 0 || MyUtils.trim(pval) == 0) {
			MyUtils.info("请输入优惠数量  和 优惠价格");
			return;
		}
	}
	appendYhDiv($('#subYh').children().length + 1);
};

/**
 * 将知道id的内容转换成int
 */
var toInt = function(id) {
	var val = $('#' + id).val();
	var intV = parseInt(val);
	if(isNaN(intV)) {
		intV = 0;
	} 
	$('#' + id).val(intV);
};

/**
 * 获取数字
 */
var getNumber=function(val) {
	return isNaN(val) ? 0 :val;
};
